package com.st.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.st.config.WeixinConfig;
import com.st.entity.Attractions;
import com.st.entity.Order;
import com.st.entity.Result;
import com.st.mapper.IOrderMapper;
import com.st.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<IOrderMapper, Order> implements IOrderService {

    @Autowired
    private IOrderMapper iOrderMapper;

    @Override
    public Order findOrderById(String id) {
        return iOrderMapper.findOrderById(id);
    }

    @Override
    public Result pay(String id) {
        //1：计算fee
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Order items = iOrderMapper.selectOne(queryWrapper);
        Integer fee = 0;
        fee = (int)(items.getOrderMoney()*100);
        //调用微信的统一下单接口
        try {
            String codeUrl = unifiedorder(id, 1, "http://wylp.free.idcfengye.com/weixin/notify");
            if (codeUrl == null) {
                return new Result(false,"下单失败");
            }
            //返回数据
            Map data = new HashMap();
            data.put("codeUrl",codeUrl);
            data.put("fee",fee);
            return  new Result(true,"下单成功",data);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,"下单失败");
        }
    }

    @Override
    public Result queryOrderStatus(String orderId) {
        Order order = iOrderMapper.selectById(orderId);
        return order!=null?new Result(true,"查询成功",order.getOrderStatu()):new Result(false,"查询失败，无此订单");
    }

    private String unifiedorder(String orderId,Integer fee,String notifyUrl) throws Exception {
        //调用统一下单接口
        WeixinConfig config = new WeixinConfig();
        //封装请求参数
        Map reqeustParams = new HashMap();
        reqeustParams.put("appid", config.getAppID());
        reqeustParams.put("mch_id", config.getMchID());
        reqeustParams.put("nonce_str", WXPayUtil.generateNonceStr());
        reqeustParams.put("body", "去看看旅行");
        reqeustParams.put("out_trade_no", orderId);
        reqeustParams.put("total_fee", fee+ "");
        reqeustParams.put("spbill_create_ip", "127.0.0.1");
        reqeustParams.put("notify_url", notifyUrl);
        reqeustParams.put("trade_type", "NATIVE");
        //将map转换成xml数据格式
        String xmlParams = WXPayUtil.generateSignedXml(reqeustParams, config.getKey());
        //发请求
        WXPayRequest request = new WXPayRequest(config);
        String xmlRes = request.requestWithoutCert("/pay/unifiedorder", UUID.randomUUID().toString(),
                xmlParams, false);
        System.out.println(xmlRes);
        //将xml结果转换成map
        Map<String, String> mapRes = WXPayUtil.xmlToMap(xmlRes);
        System.out.println("code_url==" + mapRes.get("code_url"));
        return  mapRes.get("code_url");
    }
    //支付成功查询信息
    @RequestMapping("/getInfo")
    public Result getInfo(String id){
        Order info = iOrderMapper.getInfo(id);
        if (info == null) {
            return new Result(false,"未查到");
        }
        return new Result(true,"查询成功",info);
    }

    @Override
    public Result status(String id){
        Order order = iOrderMapper.selectById(id);
        order.setOrderStatu(2);
        int i = iOrderMapper.updateById(order);
        return new Result(i==1?true:false,i==1?"修改成功":"修改失败");
    }
}
